const OSS = require('ali-oss');
const fs = require('fs');
const path = require('path');
// 初始化OSS客户端
const client = new OSS({
    // 从环境变量中获取AccessKey ID的值
    accessKeyId: "LTAI5tGzqeVah18znseETe79",
    // 从环境变量中获取AccessKey Secret的值
    accessKeySecret: "Syz5WwktW97mZhBuxNEzf7vlrIRjCE",
    // 指定OSS的Endpoint
    endpoint: 'oss-cn-chengdu.aliyuncs.com',
    // 指定Bucket名称
    bucket: 'hexo-wkq-pub'
});

async function putOSS(src, dist) {
    try {
        let result = await client.put(dist, src);
    } catch (e) {
        console.log(e);
    } finally {
        console.log("已成功部署至OSS");
    }
}

function addFileToOSSSync(src, dist) {
    // Handle case where src is a single file path (string)
    if (typeof src === 'string') {
        src = [src];
    }

    // Process each source path
    src.forEach(currentSrc => {
        // Check if the current source is a file
        const st = fs.statSync(currentSrc);

        if (st.isFile() && !currentSrc.endsWith('.DS_Store')) {
            // If it's a file, calculate the destination path
            const filename = path.basename(currentSrc);
            const _dist = path.join(dist, filename);
            putOSS(currentSrc, _dist);
        }
        else if (st.isDirectory()) {
            // If it's a directory, process all files in it
            const docs = fs.readdirSync(currentSrc);
            docs.forEach(function(doc) {
                var _src = src + '/' + doc,
                    _dist = dist + '/' + doc;
                const st = fs.statSync(_src);

                if (st.isFile() && doc !== '.DS_Store') {
                    putOSS(_src, _dist);
                }
                else if (st.isDirectory()) {
                    addFileToOSSSync(_src, _dist);
                }
            });
        }
    });
}
addFileToOSSSync( ["docs","sidebars.ts","docusaurus.config.ts"],'siteCode');

